<?php
use Workerman\Worker;
use Workerman\Lib\Timer;



// 自动加载类
require_once __DIR__ . '/Libs/Utility.php';
# 加载支付宝RSA2
require_once __DIR__ . '/Libs/Pays/aop/AopClient.php';
require_once __DIR__ . '/Libs/Pays/aop/request/AlipayTradeAppPayRequest.php';
require_once __DIR__ . '/Libs/Pays/aop/request/AlipayTradeWapPayRequest.php';
require_once __DIR__ . '/Libs/Pays/aop/request/AlipayTradePagePayRequest.php';
# 加载微信支付
require_once __DIR__ . '/Libs/Pays/wx/WxPay.Api.php';
require_once __DIR__ . '/Libs/Pays/wx/WxPay.Data.php';
# 加载二维码生成库
require_once __DIR__ . "/Libs/Qrcode.lib.php";

# 加载自定义类库
require_once __DIR__ . "/Services/Pay.php";
require_once __DIR__ . "/Services/Game.php";
require_once __DIR__ . "/Services/User.php";

require_once __DIR__ . "/Gateway.php";


// 开启的端口
$worker = new Worker('JsonNL://0.0.0.0:2016');
// 启动多少服务进程
$worker->count = 7;
// worker名称，php start.php status 时展示使用
$worker->name = 'autoWork';

$worker->onWorkerStart = function($worker)
{
    // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
    global $db;
    global $redis;
    global $utility;
    $db = \GatewayWorker\Lib\Db::instance('db');
    $redis = new \Redis();
    $redis->connect(\Config\Redis::$redis['host'], \Config\Redis::$redis['port']);
    if(isset(Config\Redis::$redis['auth'])) {
        $redis->auth(Config\Redis::$redis['auth']);
    }
    $utility = new jsonUtility($db, $redis);
    # region 自动超时
    // 每5秒执行一次
    $time_interval = 5;
    if($worker->id === 0) {
        Timer::add($time_interval, function () {
            global $db;
            global $utility;
            $nowtime = time();
            $sql = "SELECT issue,begintimes,state,gameid,room_id FROM `" . \Config\Sys::$dbprefix . "bets` WHERE ((begintimes + overtime) - {$nowtime}) < -10 AND `state`=0 ORDER BY `id` ASC";
            $red_datas = $db->query($sql);
            if( $red_datas ){
                foreach ( $red_datas as $k=>$red_data ){
                    $db_ym = date('Ym',$red_data['begintimes']);
                    # 找出对应的流水日志
                    $db->beginTrans();
                    $db->query("UPDATE `" . \Config\Sys::$dbprefix . "bets` SET `state`=2,`isauto`=1 WHERE `issue`='{$red_data['issue']}' LIMIT 1");
                    $db->query("UPDATE `" . \Config\Sys::$dbprefix . "betslog` SET `state`=2 WHERE `issue`='{$red_data['issue']}'");
                    //找出所有参与当期红包的帐变记录
                    $issue_coinlog = $db->query("SELECT `id`,`uid`,`coin`,`liqtype`,`gameid` FROM `" . \Config\Sys::$dbprefix . "coinlog_".$db_ym."` WHERE `ex2`='{$red_data['issue']}'");
                    //开始事务处理============================================
                    foreach ($issue_coinlog as $val) {
                        $utility->setCoin(array(
                                'uid' => $val['uid'],
                                'coin' => (0 - floatval($val['coin'])), //帐变扣款是负数，返回时须用0去减变回正数
                                'gameid' => $val['gameid'],
                                'liqtype' => 6, //红包超时退回
                                'ex1' => $val['id'],
                                'ex2' => $red_data['issue'],
                                'ex3' => '超时退回',
                            )
                        );
                    }
                    //echo $red_data['issue'] . "超时退回成功\n";
                    $db->commitTrans();
                    $sendData = [
                        'state' => 200,
                        'cmd'   => 'overed',
                        'gameid'=> $red_data['gameid'],
                        'issue' => $red_data['issue'],
                    ];
                    $group = 'game_'.$red_data['gameid'].'_'.$red_data['room_id'];
                    \GatewayClient\Gateway::sendToGroup($group,json_encode($sendData));
                }
            }
        });
    }
    # endregion

    # region 自动发包
    $send_times = 4;
    if($worker->id === 1){
        Timer::add($send_times, function () {
            global $db;
            global $utility;
            $games = Game::getGameList();
            foreach ($games as $gamekey => $gameval) {
                $gameid = $gameval['id'];
                $paras = array(
                    'token' => '',
                    'cmd' => 'sendred',
                    'room_id' => $gameid,
                    'game_id' => $gameid,
                    'coin' => 0,
                    'needuser' => 5,
                    'ws' => 1,
                    'pass' => '',
                    'remoteip' => '2130706433',
                );
                if ($gameid == 3) {
                    $paras['ws'] = mt_rand(1, 9);
                }

                # 抢发参数
                $sendParams = $utility->getGameSendGrabParas($gameid);

                if($sendParams['autosend']) {
                    $functionRunBeginTimes = microtime(true);
                    # 统计房间的红包数
                    $nowtime = time();
                    # $sql = "SELECT gameid,COUNT(1) AS count,GROUP_CONCAT(uid) AS uids FROM `" . \Config\Sys::$dbprefix . "bets` WHERE (`overtime` - (UNIX_TIMESTAMP() - `begintimes`)) > 0 AND `state`=0 AND `gameid`=" . $gameid;

                    $sql = "SELECT gameid,COUNT(1) AS count,GROUP_CONCAT(uid) AS uids ";
                    $sql .= "FROM `" . \Config\Sys::$dbprefix . "bets` ";
                    $sql .= "WHERE (`overtime` - (".$nowtime." - `begintimes`)) > 0 AND `state`=0 AND `gameid`=" . $gameid;

                    $gameCount = $db->row($sql);

                    # 如果红包数量已经够将不再发，继续下一个游戏
                    $maxsend = $sendParams['sendnums'];
                    $maxcount = $sendParams['sendnums'];//mt_rand(2, $maxsend);
                    if ($gameCount['count'] >= $maxcount) {
                        //echo "当前已有" . $maxcount . "个以上红包，本次操作无效……\n";
                        sleep(0.5);
                        continue;
                    }

                    $coinlist = explode(',', $sendParams['coinlist']);
                    # 设置发包金额
                    if (is_array($coinlist)) {
                        $coinlistKey = array_rand($coinlist, 1);
                        $paras['coin'] = intval($coinlist[$coinlistKey]);
                    }
                    # 取出当前的游戏不包含参数
                    $game = Game::getGameForID($gameid);
                    # 处理发包人数
                    $needUserList = explode(',', $game['manymen']);
                    if(is_array($needUserList) && count($needUserList)>1) {
                        $nuKey = array_rand($needUserList, 1);
                    }else{
                        $nuKey = 0;
                    }
                    $paras['needuser'] = $needUserList[$nuKey];

                    # 取出机器人且不能是已有发包的机器人
                    $sendNotUids = empty($gameCount['uids']) ? '' : 'NOT IN(' . $gameCount['uids'] . ')';
                    $autoSendUids = $db->row('SELECT GROUP_CONCAT(`uid`) AS uids FROM `' . \Config\Sys::$dbprefix . 'autosend` WHERE `uid` ' . $sendNotUids . ' AND `gameid`=' . $gameid, 2);
                    $autoSendUids = $autoSendUids['uids'];
                    if (empty($autoSendUids)) {
                        //echo "没有对应的发包用户\n";
                        sleep(0.5);
                        continue;
                    }
                    $autoSendUidsArr = explode(',', $autoSendUids);
                    $uidKey = array_rand($autoSendUidsArr, 1);
                    $uid = $autoSendUidsArr[$uidKey];
                    if( !$uid ){
                        sleep(0.5);
                        continue;
                    }


                    # 登录发包的用户，更新用户的token
                    $sql = "SELECT `uno`,`token`,`usertype` FROM `" . \Config\Sys::$dbprefix . "users` WHERE `uid`=" . $uid . " LIMIT 1";
                    $unotokentype = $db->row($sql);
                    $token = $utility->settoken($unotokentype['uno'], $unotokentype['token']);
                    $times = time();
                    $sql = "UPDATE `" . \Config\Sys::$dbprefix . "users` SET `webtoken`='" . $token . "', `lastlogintimes`=" . $times . " WHERE `uid`=" . $uid . " LIMIT 1";
                    $db->query($sql);
                    $paras['token'] = $token;
                    //判断机器人发包的金额-暂时写固定
                    //普通厅金币1-200，钻石厅200-2000，贵宾厅2000以上
                    if( $unotokentype['usertype'] == 0 ){
                        $rid = 4;
                    }else{
                        if( $paras['coin'] < 200 ){
                            $rid = 1;
                        }elseif ( $paras['coin'] >= 200 & $paras['coin'] < 2000 ){
                            $rid = 2;
                        }else{
                            $rid = 3;
                        }
                    }

                    $paras['rid'] = $rid;
                    $result = Game::sendGameEnvelopes($paras);
                    if ($result['state'] == 200) {
                        $beforResult = array(
                            'state' => 200,
                            'cmd' => 'newred',
                            'gameid' => $result['gameid'],
                            'datas' => $result['datas'],
                        );
                        //echo $game['title']."发包成功 - " . $result['datas']['issue'] . "，耗时：".(round(($functionRunEndTimes - $functionRunBeginTimes),3) * 1000)."ms\n";
                        # 发包后要推送到前端
                        $group = $result['groupname'].'_'.$rid;
                        \GatewayClient\Gateway::sendToGroup($result['groupname'], json_encode($beforResult));
                    }else{
                        //echo "【".$game['title']."】发包失败 - " . $result['msgid'] . "，红包数量：".$paras['needuser']."，耗时：".(round(($functionRunEndTimes - $functionRunBeginTimes),3) * 1000)."ms\n";
                    }
                }
                sleep(0.5);
            }
        });

    }
    # endregion

    # region 自动抢包
    $grab_time = 1;
    function autograb($gameid)
    {
        global $db;
        global $utility;
        $paras = array(
            'cmd' => 'grab',
            'room_id' => 1,
            'game_id' => 1,
            'red_issue' => '',
            'pass' => '',
            'token' => '',
        );

        # 抢发参数
        $sendParams = $utility->getGameSendGrabParas($gameid);
        if ($sendParams['autograb']) {
            $coinlist = explode(',', $sendParams['coinlist']);
            # 设置发包金额
            $maxcoin = $coinlist[0];
            if (is_array($coinlist)) {
                $max = count($coinlist) -1;
                $maxcoin = $coinlist[$max];
            }

            # 随机排序
            $nowtime = time();

            $sql = "SELECT `id`,`room_id` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE";
            $sql .= " `coin`<=".$maxcoin." AND `gameid`=" . $gameid . " AND ";
            $sql .= "`state`=0 AND " . $nowtime . " - `begintimes` <=180 AND `begintimes`<> {$nowtime} AND `pass`='' AND `room_id` in (1,2,3)";
            //取出普通，钻石，贵宾厅, 普通房间的红包
            $reds = $db->query($sql);
            if (!$reds) {
                sleep(0.5);
                return;
            };
            # 随机一个红包
            $redKey = array_rand($reds, 1);
            $id = $reds[$redKey]['id'];

            # 拉取当前准备抢的红包
            $sql = "SELECT `usertype`,`state`,`issue`,`gameid` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE `id`=" . $id . " LIMIT 1";
            $red = $db->row($sql);
            if (!$red && !$red['state']) {
                sleep(0.5);
                return;
            }

            if ($red['usertype'] == 0) {
                $usertype = ' AND U.`usertype`=0';
            } else {
                $usertype = ' AND U.`usertype`>=1';
            }
            # 找出已参与的玩家
            $sql = "SELECT GROUP_CONCAT(uid) AS _UIDS FROM `" . \Config\Sys::$dbprefix . "betslog` WHERE `gameid`=" . $red['gameid'] . " and `issue`='" . $red['issue'] . "'";
            $grabuser = $db->row($sql);
            $uids = empty($grabuser['_UIDS']) ? '' : ',' . $grabuser['_UIDS'];
            # var_dump($uids);
            # 这里要判断$uids是不是为空，如果没有值将取消这个抢包动作

            $sql = "SELECT U.`uid`,U.`uno`,U.`token` FROM `" . \Config\Sys::$dbprefix . "autosend` A,`" . \Config\Sys::$dbprefix . "users` U WHERE A.`uid`=U.`uid` AND A.`uid` NOT IN(0" . $uids . ") AND A.`gameid`=" . $red['gameid'] . " " . $usertype;
            # 随机取出一个机器人
            $data = $db->query($sql);
            if ($data) {
                $userKey = array_rand($data, 1); // array_rand(): Array is empty
                $user = $data[$userKey];
                if ($user) {
                    $token = $utility->settoken($user['uno'], $user['token']);
                    $times = time();
                    $sql = "UPDATE `" . \Config\Sys::$dbprefix . "users` SET `webtoken`='" . $token . "', `lastlogintimes`=" . $times . " WHERE `uid`=" . $user['uid'] . " LIMIT 1";
                    $db->query($sql);

                    $data['webtoken'] = $token;
                    $data['lastlogintimes'] = $times;

                    $paras['room_id'] = 'game_' . $gameid;
                    $paras['game_id'] = $gameid;
                    $paras['red_issue'] = $red['issue'];
                    $paras['token'] = $token;

                    $result = Game::grabGameEnvelopes($paras);

                    if (isset($result['state']) && $result['state'] == 200) {
                        # 通知玩法房间更新当期红包更新数据人数
                        if (isset($result['updatered'])) {
                            $result['updatered']['state'] = 200;
                            \GatewayClient\Gateway::sendToGroup($result['groupname'], json_encode($result['updatered']));
                        }
                        # 通知当前期数房间有新玩家加入抢包
                        if (isset($result['newsjoingrab'])) {
                            // Gateway::joinGroup($client_id, $data['reddata']['issue']);
                            \GatewayClient\Gateway::sendToGroup($result['reddata']['issue'], json_encode($result['newsjoingrab']));
                        }
                        $result['datas'] = $result['reddata'];
                        unset($result['reddata']);
                        unset($result['updatered']);
                        unset($result['newsjoingrab']);
                        $settlement = (isset($result['settlement']) ? $result['settlement'] : false);
                        unset($result['settlement']);

                        if ($settlement && isset($settlement['issue'])) {
                            \GatewayClient\Gateway::sendToGroup($settlement['issue'], json_encode($settlement));
                        }
                    }
                }
            }
        }
    }
    // $sleepTimes = mt_rand(50,($sendParams['grabtimes']*100));
    // $sleepTimes = $sleepTimes / 100;
    $room_time_interval = 3;
    if($worker->id === 2){
        Timer::add($grab_time, 'autograb', array(1), true);
        Timer::add($grab_time, 'autograb', array(2), true);
        Timer::add($grab_time, 'autograb', array(3), true);
        Timer::add($grab_time, 'autograb', array(4), true);
        Timer::add($grab_time, 'autograb', array(5), true);
        Timer::add($room_time_interval, 'autoroom', array(5), true);
    }
    # endregion

    # region 充值自动确认
    $recharge_time_interval = 10;
    if($worker->id === 3){
        Timer::add($recharge_time_interval, function () {
            global $db;
            global $redis;
            global $utility;

            # 自动确认充值 - 充值时间是 2分钟之前的2分钟内没有确认的存款记录
            $rechargeBegintims = strtotime("-2 minute");
            $rechargeEndtimes = strtotime("-4 minute");

            # 查找paywayid > 2 即除了管理员充值和银行存款外的存款记录
            # $sql = "SELECT `rechargeid` FROM `" . \Config\Sys::$dbprefix . "users_recharge` WHERE `state`=0 AND `paywayid`>2 AND `actiontime`>=".$rechargeEndtimes." AND `actiontime`<=" . $rechargeBegintims ." ORDER BY `id` DESC";
            $sql = "SELECT `rechargeid` FROM `" . \Config\Sys::$dbprefix . "users_recharge` WHERE `state`=0 AND `paywayid`>2 ORDER BY `id` DESC";

            $recharges = $db->query($sql);
            foreach ( $recharges as $recharge ){
                if($recharge){
                    $result = Pay::publicOrderQuery(array(
                        'orderid' => $recharge['rechargeid']
                    ));
                }
            }


            # 删除概率库的缓存
            $redis_key = \Config\Sys::$redisKey['UPLIST'];
            $redis->del($redis_key);
        });
    }
    # endregion

    #region 检查新建的房间
    function autoroom(){
        global $db;
        $sql = "select * from rp_rooms_game where status=1";
        $data = $db->query($sql);
        $now = time();
        if( $data ){
            foreach ( $data as $k=>$v){
                if( $now > $v['endtimes'] ){ //房间结束
                    $db->query("update rp_rooms_game set `status`='2' where id={$v['id']}");
                    $sendData = [
                        'state' => 200,
                        'cmd'   => 'updaterooms',
                        'room_id'   => $v['id']
                    ];
                    \GatewayClient\Gateway::sendToGroup('room_'.$v['game_id'],json_encode($sendData));
                }
            }
        }
    }
    #endregion

    #region 自动创建房间
    $creategameroom_time = 2;
    if( $worker->id === 4 ){
        Timer::add($creategameroom_time,function (){
            global $db;
            global $utility;
            $games = Game::getGameList();
            foreach ( $games as $gamekey => $gameval ){
                $gameid = $gameval['id'];
                $sendParams = $utility->getGameSendGrabParas($gameid);
                $nowtime = time();
                if($sendParams['autocreate']) {
                    $sql = "SELECT game_id,COUNT(1) AS count,GROUP_CONCAT(uid) AS uids ";
                    $sql .= "FROM `" . \Config\Sys::$dbprefix . "rooms_game` ";
                    $sql .= "WHERE `endtimes` >= {$nowtime} AND `status`=1 AND `game_id`=" . $gameid;
                    $roomCount = $db->row($sql);
                    $maxsend = $sendParams['createroomnums'];
                    $maxcount = $sendParams['createroomnums'];//mt_rand(2, $maxsend);
                    if ($roomCount['count'] >= $maxcount) {
                        //echo "当前已有" . $maxcount . "个以上房间，本次操作无效……\n";
                        sleep(0.5);
                        continue;
                    }
                    # 取出机器人且不能是已有房间的机器人
                    $createNotUids = empty($roomCount['uids']) ? '' : 'NOT IN(' . $roomCount['uids'] . ')';
                    $autoCreateUids = $db->row('SELECT GROUP_CONCAT(`uid`) AS uids FROM `' . \Config\Sys::$dbprefix . 'autosend` WHERE `uid` ' . $createNotUids . ' AND `gameid`=' . $gameid, 2);
                    if (empty($autoCreateUids['uids'])) {
                        //echo "没有对应的游戏用户\n";
                        sleep(0.5);
                        continue;
                    }
                    $autocreateUidsArr = explode(',', $autoCreateUids['uids']);
                    //随机取得一个用户
                    $uidKey = array_rand($autocreateUidsArr, 1);
                    $uid = $autocreateUidsArr[$uidKey];

                    $sql = "SELECT `uno`,`token`,`webtoken` FROM `" . \Config\Sys::$dbprefix . "users` WHERE `uid`=" . $uid . " LIMIT 1";
                    $unotoken = $db->row($sql);
                    $paras = [
                        'cmd'       => 'createroom',
                        'token'     => $unotoken['webtoken'],
                        'game_id'   => $gameid,
                        'uid'       => $uid,
                        'time'      => mt_rand(50,2400) / 100,//0.5-24 小时
                        'pass'      => '0000',
                        'name'      => $utility->roundRoomName(),
                    ];
                    User::createRoom($paras);
                }
                sleep(1);
            }
        });
    }
    #endregion

    # region 自动抢包 - 2
    $grab_time = 2;
    function autograb2($gameid)
    {
        global $db;
        global $utility;
        $paras = array(
            'cmd' => 'grab',
            'room_id' => 1,
            'game_id' => 1,
            'red_issue' => '',
            'pass' => '',
            'token' => '',
        );
        # 抢发参数
        $sendParams = $utility->getGameSendGrabParas($gameid);
        if ($sendParams['autograb']) {
            $coinlist = explode(',', $sendParams['coinlist']);
            # 设置发包金额
            $maxcoin = $coinlist[0];
            if (is_array($coinlist)) {
                $max = count($coinlist) -1;
                $maxcoin = $coinlist[$max];
            }

            # 随机排序
            $nowtime = time();
            # $sql = "SELECT `id` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE `coin`<=".$maxcoin." AND `gameid`=" . $gameid . " AND `state`=0 AND UNIX_TIMESTAMP() - `begintimes` <=180 AND `pass`=''";
            $sql = "SELECT `id` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE";
            $sql .= " `coin`<=".$maxcoin." AND `gameid`=" . $gameid . " AND ";
            $sql .= "`state`=0 AND " . $nowtime . " - `begintimes` <=180 AND `begintimes`<> {$nowtime} AND `usertype`>0 AND `pass`='' AND `room_id` in (1,2,3)";
            //取出普通，钻石，贵宾厅的红包
            $reds = $db->query($sql);
            if (!$reds) {
                sleep(0.5);
                return;
            };
            # 随机一个红包
            $redKey = array_rand($reds, 1);
            $id = $reds[$redKey]['id'];

            # 拉取当前准备抢的红包
            $sql = "SELECT `usertype`,`state`,`issue`,`gameid` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE `id`=" . $id . " LIMIT 1";
            $red = $db->row($sql);
            if (!$red && !$red['state']) {
                sleep(0.5);
                return;
            }

            if ($red['usertype'] == 0) {
                $usertype = ' AND U.`usertype`=0';
            } else {
                $usertype = ' AND U.`usertype`>=1';
            }
            # 找出已参与的玩家
            $sql = "SELECT GROUP_CONCAT(uid) AS _UIDS FROM `" . \Config\Sys::$dbprefix . "betslog` WHERE `gameid`=" . $red['gameid'] . " and `issue`='" . $red['issue'] . "'";
            $grabuser = $db->row($sql);
            $uids = empty($grabuser['_UIDS']) ? '' : ',' . $grabuser['_UIDS'];
            # var_dump($uids);
            # 这里要判断$uids是不是为空，如果没有值将取消这个抢包动作

            $sql = "SELECT U.`uid`,U.`uno`,U.`token` FROM `" . \Config\Sys::$dbprefix . "autosend` A,`" . \Config\Sys::$dbprefix . "users` U WHERE A.`uid`=U.`uid` AND A.`uid` NOT IN(0" . $uids . ") AND A.`gameid`=" . $red['gameid'] . " " . $usertype;
            # 随机取出一个机器人
            $data = $db->query($sql);
            if ($data) {
                $userKey = array_rand($data, 1); // array_rand(): Array is empty
                $user = $data[$userKey];
                if ($user) {
                    $token = $utility->settoken($user['uno'], $user['token']);
                    $times = time();
                    $sql = "UPDATE `" . \Config\Sys::$dbprefix . "users` SET `webtoken`='" . $token . "', `lastlogintimes`=" . $times . " WHERE `uid`=" . $user['uid'] . " LIMIT 1";
                    $db->query($sql);

                    $data['webtoken'] = $token;
                    $data['lastlogintimes'] = $times;

                    $paras['room_id'] = 'game_' . $gameid;
                    $paras['game_id'] = $gameid;
                    $paras['red_issue'] = $red['issue'];
                    $paras['token'] = $token;

                    $result = Game::grabGameEnvelopes($paras);

                    if (isset($result['state']) && $result['state'] == 200) {
                        # 通知玩法房间更新当期红包更新数据人数
                        if (isset($result['updatered'])) {
                            $result['updatered']['state'] = 200;
                            \GatewayClient\Gateway::sendToGroup($result['groupname'], json_encode($result['updatered']));
                        }
                        # 通知当前期数房间有新玩家加入抢包
                        if (isset($result['newsjoingrab'])) {
                            // Gateway::joinGroup($client_id, $data['reddata']['issue']);
                            \GatewayClient\Gateway::sendToGroup($result['reddata']['issue'], json_encode($result['newsjoingrab']));
                        }
                        $result['datas'] = $result['reddata'];
                        unset($result['reddata']);
                        unset($result['updatered']);
                        unset($result['newsjoingrab']);
                        $settlement = (isset($result['settlement']) ? $result['settlement'] : false);
                        unset($result['settlement']);

                        if ($settlement && isset($settlement['issue'])) {
                            \GatewayClient\Gateway::sendToGroup($settlement['issue'], json_encode($settlement));
                        }
                    }
                }
            }
        }
        sleep(0.5);
    }

    if($worker->id === 5){
        Timer::add($grab_time, 'autograb2', array(1), true);
        Timer::add($grab_time, 'autograb2', array(2), true);
        Timer::add($grab_time, 'autograb2', array(3), true);
        Timer::add($grab_time, 'autograb2', array(4), true);
        Timer::add($grab_time, 'autograb2', array(5), true);
        Timer::add($grab_time, 'autograb2', array(3), true);
    }
    # endregion

    # region 自动抢包 -3
    $grab_time = 2;
    function autograb3($gameid)
    {
        global $db;
        global $utility;
        $paras = array(
            'cmd' => 'grab',
            'room_id' => 1,
            'game_id' => 1,
            'red_issue' => '',
            'pass' => '',
            'token' => '',
        );

        # 抢发参数
        $sendParams = $utility->getGameSendGrabParas($gameid);
        if ($sendParams['autograb']) {
            $coinlist = explode(',', $sendParams['coinlist']);
            # 设置发包金额
            $maxcoin = $coinlist[0];
            if (is_array($coinlist)) {
                $max = count($coinlist) -1;
                $maxcoin = $coinlist[$max];
            }

            # 随机排序
            $nowtime = time();
            # $sql = "SELECT `id` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE `coin`<=".$maxcoin." AND `gameid`=" . $gameid . " AND `state`=0 AND UNIX_TIMESTAMP() - `begintimes` <=180 AND `pass`=''";
            $sql = "SELECT `id`,`room_id` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE";
            $sql .= " `coin`<=".$maxcoin." AND `gameid`=" . $gameid . " AND ";
            $sql .= "`state`=0 AND " . $nowtime . " - `begintimes` <=180 AND `begintimes`<> {$nowtime} AND `pass`='' AND `room_id` not in (0,1,2,3,4)";
            //取出普通，钻石，贵宾厅, 普通房间的红包
            $reds = $db->query($sql);
            if (!$reds) {
                sleep(0.5);
                return;
            };
            # 随机一个红包
            $redKey = array_rand($reds, 1);
            $id = $reds[$redKey]['id'];
            $room_id = $reds[$redKey]['room_id'];

            $sql = "SELECT `pass` FROM `" . \Config\Sys::$dbprefix . "rooms_game` WHERE `id`=" . $room_id . " LIMIT 1";
            $room = $db->row($sql);

            if($room['pass'] == ''){
                # 拉取当前准备抢的红包
                $sql = "SELECT `usertype`,`state`,`issue`,`gameid` FROM `" . \Config\Sys::$dbprefix . "bets` WHERE `id`=" . $id . " LIMIT 1";
                $red = $db->row($sql);
                if (!$red && !$red['state']) {
                    sleep(0.5);
                    return;
                }

                if ($red['usertype'] == 0) {
                    $usertype = ' AND U.`usertype`=0';
                } else {
                    $usertype = ' AND U.`usertype`>=1';
                }
                # 找出已参与的玩家
                $sql = "SELECT GROUP_CONCAT(uid) AS _UIDS FROM `" . \Config\Sys::$dbprefix . "betslog` WHERE `gameid`=" . $red['gameid'] . " and `issue`='" . $red['issue'] . "'";
                $grabuser = $db->row($sql);
                $uids = empty($grabuser['_UIDS']) ? '' : ',' . $grabuser['_UIDS'];
                # var_dump($uids);
                # 这里要判断$uids是不是为空，如果没有值将取消这个抢包动作

                $sql = "SELECT U.`uid`,U.`uno`,U.`token` FROM `" . \Config\Sys::$dbprefix . "autosend` A,`" . \Config\Sys::$dbprefix . "users` U WHERE A.`uid`=U.`uid` AND A.`uid` NOT IN(0" . $uids . ") AND A.`gameid`=" . $red['gameid'] . " " . $usertype;
                # 随机取出一个机器人
                $data = $db->query($sql);
                if ($data) {
                    $userKey = array_rand($data, 1); // array_rand(): Array is empty
                    $user = $data[$userKey];
                    if ($user) {
                        $token = $utility->settoken($user['uno'], $user['token']);
                        $times = time();
                        $sql = "UPDATE `" . \Config\Sys::$dbprefix . "users` SET `webtoken`='" . $token . "', `lastlogintimes`=" . $times . " WHERE `uid`=" . $user['uid'] . " LIMIT 1";
                        $db->query($sql);

                        $data['webtoken'] = $token;
                        $data['lastlogintimes'] = $times;

                        $paras['room_id'] = 'game_' . $gameid;
                        $paras['game_id'] = $gameid;
                        $paras['red_issue'] = $red['issue'];
                        $paras['token'] = $token;

                        $result = Game::grabGameEnvelopes($paras);

                        if (isset($result['state']) && $result['state'] == 200) {
                            # 通知玩法房间更新当期红包更新数据人数
                            if (isset($result['updatered'])) {
                                $result['updatered']['state'] = 200;
                                \GatewayClient\Gateway::sendToGroup($result['groupname'], json_encode($result['updatered']));
                            }
                            # 通知当前期数房间有新玩家加入抢包
                            if (isset($result['newsjoingrab'])) {
                                // Gateway::joinGroup($client_id, $data['reddata']['issue']);
                                \GatewayClient\Gateway::sendToGroup($result['reddata']['issue'], json_encode($result['newsjoingrab']));
                            }
                            $result['datas'] = $result['reddata'];
                            unset($result['reddata']);
                            unset($result['updatered']);
                            unset($result['newsjoingrab']);
                            $settlement = (isset($result['settlement']) ? $result['settlement'] : false);
                            unset($result['settlement']);

                            if ($settlement && isset($settlement['issue'])) {
                                \GatewayClient\Gateway::sendToGroup($settlement['issue'], json_encode($settlement));
                            }
                        }
                    }
                }
            }
        }
    }
    if($worker->id === 6){
        Timer::add($grab_time, 'autograb3', array(1), true);
        Timer::add($grab_time, 'autograb3', array(2), true);
        Timer::add($grab_time, 'autograb3', array(3), true);
        Timer::add($grab_time, 'autograb3', array(4), true);
        Timer::add($grab_time, 'autograb3', array(5), true);
    }
    # endregion
};

// 如果不是在根目录启动，则运行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}
